package GEMonitor;

import GEMonitor.em.MsgType;
import io.netty.channel.Channel;

//import java.util.Arrays;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
//import io.netty.util.AttributeKey;

public class GEServerHandler extends SimpleChannelInboundHandler<GEMsg> {
    //private final AttributeKey<String> systemID = AttributeKey.valueOf("systemID");
    //private final AttributeKey<String> puzzer = AttributeKey.valueOf("puzzer");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GEMsg msg) throws Exception {
        try {
            if(ctx == null || msg == null)
            {
                return;
            }
            Channel channel = ctx.channel();
            if(channel != null && channel.isActive()) 
            {
                GEKafkaProducer.send(msg.systemID,msg.msg_type, msg.content);



                GEChannelMgr.getInstance().addReport(msg,channel);
//                //心跳帧
                if(msg.msg_type.equals(MsgType.HEART_BEAT.getValue())) {
                    GEMsg msg1 = new GEMsg();
                    msg1.msg_type = msg.msg_type;
                    msg1.systemID = msg.systemID;
                    msg1.content = "OK".getBytes();

                    ctx.writeAndFlush(msg1);
                }
            }    
        } catch (Exception e) {
            MyLogger.Error("channelRead0 error: " + e.getMessage());
        }
    }

    /*
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //GEMsg msg = new GEMsg();
        //msg.msg_type = "Q0";
        //msg.content = "ID!".getBytes();

        //ctx.writeAndFlush(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String sysID = ctx.channel().attr(systemID).get();
        if(sysID != null)
        {
            GEChannelMgr.getInstance().delChannel(sysID);

            GEMsg rq = new GEMsg();
            rq.msg_type = "Z0";
            rq.systemID = sysID;
            rq.content = "Disconnected".getBytes();
            GEChannelMgr.getInstance().addReport(rq);
        }
        //Channel channel = ctx.channel();
        //if(channel.isActive()) ctx.close();
    }


    @Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        
		Channel channel = ctx.channel();
		if(channel.isActive()) ctx.close();
	}
    */
}